package my.algo.tree;

/**
 * 大顶堆
 */
public class BinaryHeap {

    private final int[] arr = new int[16];
    private int count = 0;

    public void add(int val) {
        if (count >= arr.length) {
            // 应该扩容
            throw new RuntimeException();
        }
        arr[count++] = val;
        upAdjust();
        print();
    }

    private void upAdjust() {
        int childIdx = count - 1;
        int parentIdx = (childIdx - 1) / 2;
        while (childIdx > 0) {
            if (arr[childIdx] <= arr[parentIdx]) {
                break;
            }
            int temp = arr[childIdx];
            arr[childIdx] = arr[parentIdx];
            arr[parentIdx] = temp;
            childIdx = parentIdx;
            parentIdx = (childIdx - 1) / 2;
        }
    }

    public int getAndDelMax() {
        if (count == 0) {
            throw new RuntimeException();
        }
        int res = arr[0];
        arr[0] = arr[--count];
        // 只有一个元素时不需要调整
        if (count > 1) {
            downAdjust();
        }
        print();
        return res;
    }

    private void downAdjust() {
        int parentIdx = 0;
        int childIdx = 1;
        while (childIdx < count) {
            if ((childIdx + 1) < count && arr[childIdx + 1] > arr[childIdx]) {
                childIdx++;
            }
            if (arr[childIdx] <= arr[parentIdx]) {
                break;
            }
            int temp = arr[parentIdx];
            arr[parentIdx] = arr[childIdx];
            arr[childIdx] = temp;
            parentIdx = childIdx;
            childIdx = 2 * parentIdx + 1;
        }
    }

    public void print() {
        for (int i = 0; i < count; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        BinaryHeap heap = new BinaryHeap();
        heap.add(3);
        heap.add(5);
        heap.add(10);
        heap.add(2);
        heap.add(7);
        heap.add(20);
        heap.add(17);

        int res = heap.getAndDelMax();
        res = heap.getAndDelMax();
        res = heap.getAndDelMax();
        res = heap.getAndDelMax();
        res = heap.getAndDelMax();
        res = heap.getAndDelMax();
        res = heap.getAndDelMax();
    }
}
